package com.ecp.commons.interceptor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;

public class LoggingControllerAroundAdvister {

	public static List<String>			runningControllerList	= new ArrayList<String>();
	public static Map<String, Integer>	ctrlerConnMap			= new HashMap<String, Integer>();
	private static boolean				isFirst					= false;

	static Logger						logger					= Logger.getLogger(LoggingControllerAroundAdvister.class);

	public Object invoke(MethodInvocation methodInvocation) throws Throwable {

		StringBuilder _key = new StringBuilder();
		_key.append(Thread.currentThread().getName() + " - " + Thread.currentThread().getId());
		ctrlerConnMap.put(_key.toString(), 0);

		Object[] obj = methodInvocation.getArguments();
		HttpServletResponse response = (HttpServletResponse) obj[1];

		if (!isFirst) {
			isFirst = true;
		}

		String threadName = Thread.currentThread().getName();

		Object returning = null;
		long flag = System.currentTimeMillis();
		StringBuilder key = new StringBuilder();

		try {
			key = new StringBuilder(flag + "-");
			key.append(methodInvocation.getThis().getClass().toString() + "-");
			key.append(methodInvocation.getMethod().getName() + "-");
			key.append(threadName);

			runningControllerList.add(key.toString());

			returning = methodInvocation.proceed();

			if (response == null || returning == null) {
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			int count = ctrlerConnMap.get(_key.toString());
			if (count >= 10) {
				logger.info(methodInvocation.getThis().getClass().toString().replaceAll("^.*\\.", "") + "\t\t" + count);
			}
			runningControllerList.remove(key.toString());
		}
		return returning;
	}

	public static List<String> lookRunningControllerList() {
		return runningControllerList;
	}

	public static void interrupt(String threadName) {
		if (threadName == null || threadName.trim().equals("")) {
			return;
		}
		new Thread(threadName).interrupt();
	}
}
